<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Menus extends MX_Controller 
{
    private $menu_types = array('blank', 'url', 'page', 'module');
	public function __construct()
	{
		parent::__construct();		
		$this->display->set_theme('cms');		
	}
	
	public function index()
	{	
		$this->load->library('tree');	
		$this->load->model('menu_model');
		$template = $this->display->get_theme_config('site');
				
		foreach($template['menu_areas'] as $area)
		{
			$menu = $this->menu_model->get(array('area' => $area, 'sort_by' => 'order'));
			if( $menu )
            {
				$data['menus'][$area]['items'] = $this->tree->rows_to_tree($menu, 'id', 'parent');
                $data['menus'][$area]['depth'] = $template['menu_depth'][$area];
            }
		}


		$this->twiggy->title()->append('Menus');
		$this->display->template('menu_list', $data);
	}
	
    public function set_default($menu_id)
    {
        // check permission
        
        // check menu id
        if( ! ctype_digit($menu_id) )
        {
            return;
        }
        
        $this->load->model('menu_model');
        $this->menu_model->set_default($menu_id);
        
        cms_redirect('menus');
    }
	
	public function add()
	{
		$area = $this->input->post('menu_area');
		$this->display->set_theme('site');
		$areas = $this->display->get_config('menu_areas');
		if(in_array($area, $areas))
		{
			$this->load->model('menu_model');
			$result = $this->menu_model->add('New menu item', $area);
			if($result)		
			{
				flash_message('success', 'Menu item added');
				cms_redirect('menus/edit/'.$result);
			}	
			else
				flash_message('error', 'A database error occured');				
		}
		else
		{
			flash_message('error', 'An error occured');
		}		
		cms_redirect('menus');	 	
	}
    
    public function delete($menu_id)
    {
        if(ctype_digit($menu_id))
		{
			$this->load->model('menu_model');
			if($this->menu_model->delete(array('id' => $menu_id)))
			{
				flash_message('success', 'Menu item has been deleted');
			}
			else 
			{
				flash_message('error', 'Menu deletion database error');
			}
		}
		else
		{
			flash_message('error', 'An error occured');
		}
		cms_redirect('menus');
    }
    
	public function edit($id)
	{
		$data = array();
		$this->load->model('menu_model');
		$menu_item = $this->menu_model->get(array('id' => $id));
		if( ! $menu_item )
			return;
		
        // Menu names
		$supported_languages = $this->config->item('site_supported_languages');
		foreach($supported_languages as $sl)
		{
			foreach($menu_item['data']['names'] as $lang => $name)
			{
				if($lang == $sl)
				{
					$data['languages'][$sl] = $name;
				}
			}
		
			if(! isset($data['languages'][$sl]))
				$data['languages'][$sl] = $menu_item['data']['names'][$this->config->item('site_default_language')];
		}
		
		$data['menu'] = $menu_item;
		$data['types'] = $this->menu_types;
		$data['menudata'] = json_encode($menu_item['data']);
        
        // pages
		$this->load->model('page_model');
		$this->load->library('tree');
		$pages = $this->page_model->get();
		$tree = $this->tree->rows_to_tree($pages, 'page_id', 'page_parent');		
		$data['pages'] = $this->tree->tree_to_options($tree, 'page_name', 'page_id');		
		
        // modules
        //$this->load->library('radicms_modules', '', 'modules');
        foreach($this->modules->get_modules() as $module)
        {
            $data['modules'][$module->name] = $module->info();
            $data['modules'][$module->name]['routes'] = $module->routes();
        }
        
        	
        if($this->input->post())
        {
            $this->load->library('form_validation');
            foreach($supported_languages as $lang)
            {
                $this->form_validation->set_rules($lang . '_name', $lang . ' name', 'required|max_length[20]');
                $menu_data['names'][$lang] = $this->input->post($lang . '_name');
            }
            
            $this->form_validation->set_rules('type', 'Menu type', 'callback_validate_type');
            
            $valid = $this->form_validation->run();
            if($valid)
            {
                $update = array();
                $update['id'] = $id;
                $update['type'] = $this->input->post('type');
                switch($update['type'])
                {
                    case "url":
                        $menu_data['url'] = $this->input->post('url');
                        break;
                    case "page":
                        $page_id = $this->input->post('page');
                        $menu_data['page'] = array('id' => $page_id,
                                                   'url' => $this->page_model->get_route($page_id));
                        break;
                    case "blank":
                        break;
                    case "module":
                        list($module_name, $route_slug) = explode('\|', $this->input->post('module'));
                        
                        $module = $this->modules->get($module_name);
                        $route = $module->get_route_by_slug($route_slug);
                        
                        $menu_data['module'] = array('name' => $module_name, 'route_slug' => $route['slug'], 'url' => $route['url']);
                        
                        if(isset($route['items']) && !empty($route['items']))
                        {
                            $menu_data['module']['item'] = $this->input->post($route_slug . '_item');     
                        }                       
                       
                        break;                    
                }
                $update['data'] = $menu_data;
                flash_message('success', print_r($update, TRUE));             
            }
            else
            {
                flash_message('error', validation_errors());
            }
            cms_redirect('menus/edit/' . $id);
        }
		
		$this->twiggy->title()->append('Menus');
		$this->display->template('menu_edit', $data);		
		
	}

    public function validate_type($type)
    {
        if(in_array($type, $this->menu_types))
        {
            // check other stuff
            switch($type)
            {
                case "url":
                    $url = $this->input->post('url');
                    break;
                case "page":
                    $page_id = $this->input->post('page_id');
                    break;
                case "module":
                    $module = $this->input->post('module');
                    break;
            }
            
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
	
	
	public function get_data()
	{
		$type = $this->input->post('type');
		switch($type)
		{
			case "page":
				$this->load->model('page_model');
				$pages = $this->page_model->get();
				if($pages)
					foreach($pages as $page)
						$output['pages'][$page['page_id']] = $page['page_name'];
				break;
				
			case "module":
				$output = array('modules' => 
									array('character' 	=> array('index' => 'character/index', 'edit' => 'character/edit')),
									array('forum' 		=> array('index' => 'forum/index')),
								);
				break;
			
			default:
				$output = array();
				break;
		}
		
		$this->display->array_json($output);
	}
	
	public function sort()
    {
        //print_r($this->input->post());
        $this->load->model('menu_model');
        $area = $this->input->post('area');
        foreach($this->input->post('sortdata') as $index => $data)
        {
            if($data['item_id'] == NULL)
                continue;
           
            
            $this->menu_model->update(array('id' => (int) $data['item_id'],
                                            'parent' => (int) ($data['parent_id'] == NULL ? 0 : $data['parent_id']),
                                            'order' => $index
                                            ));
        }
    }
    
	public function data()
	{
		$ar = array('names' => array('english' => 'Welcome',
									 'nederlands' => 'Welkom'),
					'module' => array('name' => 'Forum index', 'controller' => 'forum', 'function' => 'index'),
					'page' => array('id' => 1, 'url' => 'Information/Rules', 'name' => 'Rules')
					);
		echo json_encode($ar);	
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */